#!/bin/zsh

action=$1
function install_nginx {
	if [ ! -d /etc/nginx ]; then
		echo "Installing nginx"
		/sbin/apk add --no-cache nginx
	fi
}

function get_pid () {
	PATTERN=$1
	/bin/ps aux|/bin/grep "${PATTERN}" | /bin/sed '/grep/d'| /usr/bin/awk '{print $1}'
}

NGINX_PATTERN="nginx: master process"

function status_nginx () {
	PID=$(/bin/ps aux|/bin/grep "nginx: master process" | /bin/sed '/grep/d'| /usr/bin/awk '{print $1}')
	echo "nginx is running with pid $PID"
}

function start_nginx () {
	install_nginx
	PID=$(get_pid ${NGINX_PATTERN})
	if [ -z ${PID} ]; then
		echo -n "start nginx "
		/usr/sbin/nginx
		PID=$(get_pid ${NGINX_PATTERN})
		echo "with pid ${PID}: [ "${GREEN_START}"OK"${GREEN_STOP}" ]"
	else
		echo -n "nginx is running with pid ${PID}: "
		echo "[ "${GREEN_START}"OK"${GREEN_STOP}" ]"
	fi
}

function reload_nginx () {
	echo "reload nginx service"
	/usr/sbin/nginx -s reload
}

case "$action" in
	status)
		status_nginx
		;;
	start)
		start_nginx
		;;
	reload)
		reload_nginx
		;;
	*)
esac
